<template>
  <div :class="{ night_mode: isNight }" class="wrapper">
    <div class="sub_title">
      <div class="safe_area_box"></div>
      <div class="tit_txt">
        <div class="ic"><i style="font-size: 18px;" :class="{ night_mode: isNight }"
            class="iconfont lricon-fanhui1"></i>
        </div>
        <span :class="{ night_mode: isNight }"> {{ currentBook.title }}</span>
        <div @click.stop="showSearch = true" class="ic"><i :class="{ night_mode: isNight }" style="font-size: 18rem;"
            class="iconfont lricon-sousuo"></i></div>
      </div>
    </div>
    <VanOverlay :lazy-render="false" :show="showSettings" @click="showSettings = false">
      <transition name="van-slide-up">
        <div v-show="showSettings" @click.stop="" class="read_settings">
          <div class="set_item">
            <div class="left">
              <div class="icon"><i class="iconfont lricon-zitidaxiao"></i></div><span>字体大小:</span> <van-stepper
                style="margin-left: 10px;" @change="changeFsize" input-width="60px" button-size="24px" v-model="txtSize"
                step="0.1" :decimal-length="1" />
            </div>
          </div>
          <div class="set_item">
            <div class="left">
              <div class="icon"><i class="iconfont lricon-38" style="font-size: 20px;"></i></div>
              <span>背景颜色:</span><input type="text" v-model="bgColor"></input>
            </div>
            <color-picker @pureColorChange="changeBgC" :round-history="true" picker-type="chrome" shape="circle"
              lang="ZH-cn" v-model:pureColor="bgColor" v-model:gradientColor="gradientColor" />
          </div>
          <div class="set_item">
            <div class="left">
              <div class="icon"><i style="font-size: 18px;" class="iconfont lricon-wenziyanse"></i></div>
              <span>字体颜色:</span><input v-model="txtColor" type="text"></input>
            </div>
            <color-picker @pureColorChange="changeTxtC" :round-history="true" picker-type="chrome" shape="circle"
              lang="ZH-cn" v-model:pureColor="txtColor" v-model:gradientColor="gradientColor" />
          </div>
          <div class="set_item">
            <div class="left">
              <div class="icon"><i class="iconfont lricon-yejianmoshi"></i></div><span>当前进度:</span>

            </div>
            <van-slider style="flex-grow: 1; max-width: 150px; margin-left: 10px;margin-right: 5vw;" bar-height="8px"
              active-color="red" v-model="processButV">
              <template #button>
                <div class="custom-button">{{ processButV }}</div>
              </template>
            </van-slider>
          </div>

        </div>
      </transition>
    </VanOverlay>

    <transition name="van-slide-right">
      <div v-show="showSearch" class="search_box">
        <div class="s_input">
          <input @keydown="search" v-model="searchKeyword" type="search"><i @click="cancelSearch"
            class="iconfont lricon-guanbi"></i>
        </div>
        <div class="searchResults">总共搜到{{ this.searchResults.length }}条结果</div>
        <div class="maodian">
          <div v-for="i in searchResults" class="itm"><a :href="i.link">{{ i.before }}<span style="color: red;">{{
            i.keyword
                }}</span>{{ i.after }}</a></div>
        </div>
      </div>
    </transition>
    <div v-touch:hold="longtap" class="wrapper_content" v-touch:swipe.down="onSwipe" v-touch-options="touchOptions">

      <transition name="slide-right">
        <div v-show="showMuLu" :class="{ night_mode: isNight }" class="book_mulu">
          <div class="rd_menu">
            <h2 style="">阅读进度</h2>
          </div>
          <div class="ydjd">
            <van-progress style="width: 34vw;" :color="stepC" :percentage="scrollPercent" />
          </div>
          <div class="fgx"></div>
          <div class="mulu_content">
            <div class="mulu_tit">目录</div>
            <div :class="{ night_mode: isNight }" class="content">
              <div v-for="(item, index) in aTagList" class="aw"><a  :href="item.href">{{ item.text }}</a></div>
            </div>
          </div>
          <div class="night">
            <i style="font-size: 23px;" class="iconfont lricon-yejianmoshi"></i><span>夜晚</span>
            <VanSwitch style="margin-left: 3vw;" v-model:model-value="isNight" size="20px" active-color="#ee0a24"
              inactive-color="whitesmoke"></VanSwitch>
          </div>
        </div>
      </transition>
      <transition name="van-fade">
        <div @scroll="handleScroll" :class="{ slcMuLu: showMuLu }" ref="bookc" v-html="bookContent"
          class="book_content">
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { getCurrentBook } from "../api/ziLiao";
import { getAllATag, getMatchResults, processHightLightHtml } from "../api/bookRead";
import { ColorPicker } from "vue3-colorpicker";
import { onBackKeyDown } from "tauri-plugin-app-events-api";
import Vue3TouchEvents from "vue3-touch-events";
import { Overlay, Progress, Stepper, Switch, Slider } from "vant";
import { getAppStore } from "../api/store";
import { updateBookopentime, updateBookpercent } from "../api/dbUtils";
export default {
  name: "Test",
  components: {
    VanOverlay: Overlay,
    VanProgress: Progress,
    ColorPicker,
    VanStepper: Stepper,
    VanSwitch: Switch,
    VanSlider: Slider,
  },
  data() {
    return {
      bookContent: '',
      showMuLu: false,
      touchOptions: {
        swipeTolerance: 70, // 滑动距离阈值
        longTapTimeInterval: 400, // 长按时间阈值
      },
      showSettings: false,
      gradientColor: "linear-gradient(0deg, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%)",
      bgColor: 'red',
      txtColor: 'red',
      txtSize: 14.5,
      isNight: false,
      stepC: '',
      scrollTop: 0,        // 滚动距离顶部的距离
      scrollHeight: 0,     // 内容总高度
      clientHeight: 0,     // 可视区域高度
      scrollPercent: 0,    // 滚动进度百分比
      aTagList: [],
      searchResults: [],
      searchKeyword: '',
      showSearch: false,
      processButV: 0,
      currentBook: null
    };
  },
  async created() {
       let store = await getAppStore()
      let settings = await store.get('appSettings')
    this.txtColor = settings.lr_rd_txt_color
    this.bgColor = settings.lr_rd_bgc
      this.txtSize = settings.lr_rd_txt_size

    let tit = this.$route.query.title
    let showsh = this.$route.query.showSearch
    let keyw = this.$route.query.keyword
    this.currentBook = await getCurrentBook(tit)
   
    this.processButV = this.currentBook.percent
    this.scrollPercent = this.currentBook.percent
    await updateBookopentime(new Date().getTime(),this.currentBook.id)
    this.bgColor = document.documentElement.style.getPropertyValue('--lr_rdbgc')
    this.txtColor = document.documentElement.style.getPropertyValue('--lr_rdtxtc')
    this.stepC = document.documentElement.style.getPropertyValue('--lr_dcbgc')
    onBackKeyDown(() => {
      if (this.showMuLu == true || this.showSearch == true || this.showSettings == true) {
        this.showMuLu = false
        this.showSearch = false
        this.showSettings = false
        return false
      }
      this.$router.push('/')
      return false;
    })

    this.bookContent = this.currentBook.zhengwen.replace(/&lt;/gi, '<')
      .replace(/&gt;/gi, '>')
      .replace(/&quot;/gi, '"')
    this.aTagList = getAllATag(this.bookContent)
    if (showsh == 'true') {
       this.showSearch = true,
    this.searchKeyword = keyw
     this.searchResults = getMatchResults(keyw, this.bookContent, 10)
    this.bookContent = processHightLightHtml(keyw, this.currentBook.zhengwen)
     }
    
  },

  props: {},
  methods: {
    longtap() {
      this.showSettings = true
    },
    async changeTxtC() {
        let store = await getAppStore()
      let settings = await store.get('appSettings')
      settings.lr_rd_txt_color = this.txtColor
      await store.set('appSettings',settings)
      document.documentElement.style.setProperty('--lr_rdtxtc', this.txtColor);
    },
   async changeBgC() {
   let store = await getAppStore()
      let settings = await store.get('appSettings')
      settings.lr_rd_bgc = this.bgColor
      await store.set('appSettings',settings)
      document.documentElement.style.setProperty('--lr_rdbgc', this.bgColor);
    },
    onSwipe(direction) {
      if (direction == 'right') {
        if (this.showSearch == true) {
          this.showSearch = false
        } else {
          this.showMuLu = true
        }
      } else if (direction == 'left') {
        if (this.showMuLu == true) {
          this.showMuLu = false
        } else {
          this.showSearch = true
        }
      }
    },
    async changeFsize() {
      let store = await getAppStore()
      let settings = await store.get('appSettings')
      settings.lr_rd_txt_size = this.txtSize
      await store.set('appSettings',settings)
      document.documentElement.style.setProperty('--lr_rdfs', this.txtSize + 'rem');
    },
    async handleScroll(e) {
      const scrollEl = e.target

      // 更新滚动数据
      this.scrollTop = scrollEl.scrollTop
      this.scrollHeight = scrollEl.scrollHeight
      this.clientHeight = scrollEl.clientHeight
      let tempper = 0;
      // 计算滚动进度
      const scrollable = scrollEl.scrollHeight - scrollEl.clientHeight
      this.scrollPercent = scrollable > 0
        ? Math.round((scrollEl.scrollTop / scrollable) * 100)
        : 0
      tempper = this.scrollPercent
      await updateBookpercent(tempper,this.currentBook.id)

    },
    async search(event) {
      if (event.key === 'Enter') {
        if (this.searchKeyword == '') {
          return;
        }
        this.searchResults = getMatchResults(this.searchKeyword, this.bookContent, 10)
        this.bookContent = processHightLightHtml(this.searchKeyword, this.currentBook.zhengwen.replace(/&lt;/gi, '<')
          .replace(/&gt;/gi, '>')
          .replace(/&quot;/gi, '"'))
      }
    },
    cancelSearch() {
      this.searchKeyword = ''
      this.bookContent = this.currentBook.zhengwen.replace(/&lt;/gi, '<')
        .replace(/&gt;/gi, '>')
        .replace(/&quot;/gi, '"')
    },
    // 滚动到指定百分比位置
    scrollToPercentage(v) {
      // 验证输入的百分比是否有效
     

      // 获取滚动容器
      const container = this.$refs.bookc;
      if (!container) return;

      // 计算目标位置：总高度 * 百分比
      // scrollHeight: 内容总高度
      // clientHeight: 容器可视高度
      const scrollableHeight = container.scrollHeight - container.clientHeight;
      const targetPosition = scrollableHeight * (v / 100);

      // 执行滚动
      container.scrollTo({
        top: targetPosition,
        behavior: 'smooth' // 平滑滚动
      })
    }
  },
  mounted() {
        this.scrollToPercentage(this.scrollPercent)
  },
  directives: {
    ...Vue3TouchEvents.directives,
  },
  watch: {
    processButV(n, o) {
      this.scrollToPercentage(n)
    }
  }
};
</script>

<style lang="scss" scoped>
$bdc: rgba($color: #ffffff, $alpha: 0.13);

.night_mode {
  background-color: #3b3a3a !important;
  color: #ffffff !important;

  p {
    color: #ffffff !important;
  }

  h {
    color: #ffffff !important;
  }

  div {
    color: #ffffff !important;
  }
}

.wrapper {
  height: 100vh;
  width: 100vw;
  background-color: var(--lr_rdbgc);
  position: fixed;
  display: flex;
  flex-direction: column;
  top: 0;
  left: 0;
  z-index: 999;
  color: var(--lr_rdtxtc);

  .read_settings {
    background-color: var(--lr_lcbgc);
    height: 20vh;
    width: 90vw;
    border-radius: 12px;
    position: fixed;
    top: 72vh;
    left: 5vw;
    padding-bottom: 2vh;
    padding-top: 2vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #000000;

    i {
      color: #000000;
    }

    .cp {
      background-color: #190202;
      margin-left: 10vw;
      height: fit-content;
      width: fit-content;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    input {
      margin-left: 10px;
      height: 24px;
      max-width: 107px;
      border-radius: 4px;
      outline: none;
      border: none;
      font-size: 14px;
      background-color: var(--lr_lbgc);
    }

    span {
      margin-left: 10px;
      font-size: 15px;
      font-weight: 600;
    }

    .set_item {
      width: 80vw;
      height: 5vh;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .custom-button {
        width: 26px;
        color: #fff;
        font-size: 10px;
        line-height: 18px;
        text-align: center;
        background-color: red;
        border-radius: 100px;
      }

      .left {
        display: flex;
        align-items: center;
        height: 5vh;

        .icon {
          width: 10vw;
          height: 5vh;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }

  .sub_title {
    border: 1px solid $bdc;
    width: 100vw;
    // background-color: var(--nav_bg_color);
    display: flex;
    flex-direction: column;
    z-index: 999;
    color: var(--lr_rdtxtc);

    .tit_txt {
      .ic {
        i {
          font-size: 20px;
          color: var(--lr_rdtxtc);

          &:active {
            transition: transform 0.3s ease;
            transform: scale(1.2)
          }
        }

        text-align: center;
        width: 14vw;
        // background-color: #531c1c;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      width: 100vw;
      height: 30px;
      line-height: 30px;
      font-size: 18px;
      font-weight: bolder;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: space-between;

      color: var(--lr_rdtxtc);
    }
  }

  .slcMuLu {
    background: rgba($color: #000000, $alpha: 0.1);
  }

  .search_box {
    height: 60vh;
    position: fixed;
    top: 30vh;
    width: 60vw;
    left: 38vw;
    background-color: #fff;
    border-radius: 10px;
    align-items: center;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .s_input {
      background-color: var(--lr_lbgc);
      color: #000000;
      margin-top: 2vw;
      display: flex;
      align-items: center;
      max-width: 56vw;
      justify-content: space-between;
      border-radius: 15px;
      height: 30px;
      overflow: hidden;

      i {
        &:active {
          transition: transform 0.3s ease;
          transform: scale(1.2)
        }
      }

      input {
        background-color: var(--lr_lbgc);
        height: 26px;
        padding-left: 5px;
        padding-right: 5px;
        outline: none;
        border: none;
        max-width: calc(50vw);
        font-size: 14px;
        flex-grow: 1;
      }

      input::-webkit-search-cancel-button {
        display: none;
      }

      i {
        color: #000000 !important;
        margin-right: 5px;
        font-size: 16px;
      }
    }

    .searchResults {
      margin-top: 10px;
      width: 56vw;
      font-size: 15px;
      height: 26px;
      font-weight: bold;
    }

    .maodian {
      flex-grow: 1;
      flex-shrink: 0;
      width: 60vw;
      display: flex;
      flex-direction: column;
      align-items: center;
      overflow: scroll;
      max-height: calc(62vh - 78px);

      .itm {
        padding-top: 5px;
        padding-bottom: 5px;
        width: 56vw;
        padding-left: 2vw;
        padding-right: 2vw;
        height: fit-content;

        &:hover {
          background-color: #efefef;
        }
      }

      a {

        border-radius: 4px;
        font-size: 14px;
        font-weight: 500;
        text-decoration: none;
        outline: none;
        cursor: default;
        height: 28px;
        line-height: 18px;
        width: 56vw;
        color: #000000 !important;
        -webkit-tap-highlight-color: transparent;

        &:active {

          text-decoration: none;
        }

        &:visited {
          text-decoration: none;
          color: inherit;
        }

        &:link {
          text-decoration: none;
        }

        &:hover {
          text-decoration: none;
        }
      }
    }
  }

  .wrapper_content {
    display: flex;
    flex-grow: 1;
    flex-shrink: 1;
    justify-content: center;
    color: var(--lr_rdtxtc);

    .book_mulu {
      height: calc(100vh - var(--safe-top) - 31px);
      width: 40vw;
      // background-color: #eff4fe;
      flex-shrink: 0;
      background-color: #var(--lr_rdbgc);
      border-right: 1px solid $bdc;
      display: flex;
      flex-direction: column;
      align-items: center;

      .night {
        width: 34vw;
        display: flex;
        align-items: center;
        height: 10vh;
        justify-content: space-between;
        font-size: 16px;
        font-weight: 600;
      }

      .rd_menu {
        width: 34vw;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 60px;
        font-size: 12px;
      }

      .ydjd {
        width: 34vw;
        margin-bottom: 3vh;
      }

      .fgx {
        width: 40vw;
        height: 1px;
        background-color: rgba($color: #ffffff, $alpha: 0.13);
      }

      .mulu_content {
        display: flex;
        flex-direction: column;
        flex-grow: 1;
        width: 34vw;

        .mulu_tit {
          width: 34vw;
          height: 30px;
          line-height: 30px;
          font-size: 18px;
          flex-shrink: 0;
          font-weight: bold;
        }

        .content {
          width: 34vw;
          padding-bottom: 10px;
        height: calc(87vh - var(--safe-top) - 111px);
          flex-shrink: 0;
          display: flex;
          overflow: scroll;
          flex-direction: column;
.aw{
width: 30vw;
            margin-top: 10px;
}
          a {
            // background: var(--lr_lbgc);
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            outline: none;
            cursor: default;
            padding-left: 2vw;
            padding-right: 2vw;
            height: 14px;
            line-height: 18px;
            
            -webkit-tap-highlight-color: transparent;

            &:active {
              // background-color: #8e8e8e;
              text-decoration: none;
            }

            &:visited {
              text-decoration: none;
              color: inherit;
            }

            &:link {
              text-decoration: none;
            }

            &:hover {
              text-decoration: none;
            }
          }
        }

      }
    }

    .book_content {
      width: fit-content;
      padding-left: 4vw;
      padding-right: 4vw;
      color: var(--lr_rdtxt);
      font-size: var(--lr_rdfs);
      height: calc(100vh - var(--safe-top) - 31px);
      flex-grow: 1;
      overflow: scroll;
    }
  }
}
</style>